import usePageStore from '@/store/pages';
import router from '.';
import { findUserRouter, userMenus } from '@/api/modules/user/utils';
import { getToken } from '@/store/user/utils';
import { currentRouter } from '@/views/admin/layout/data/router';

/**
 * @description:必须使用这个方法跳转路由
 * @param {string} path
 */
export const gotoRouter = (path: string, query?: any) => {
  if (router.hasRoute(path)) {
    router.push({
      path: `/index/${path}`,
      query,
    });
    createRouterTab(path);
  }
};

export const goHome = () => {
  const token = getToken();
  if (!token) return;
  let path = '/index/home';
  router.push(path);

  createRouterTab(path);
};

export const createRouterTab = (path: string) => {
  const pageStore = usePageStore();
  const target = findUserRouter(userMenus.value, path);
  const isExist = pageStore.$state.tabs.find(e => {
    if (e.path === path) {
      return e;
    }
  });
  if (target && !isExist) {
    currentRouter.value = target.path;
    pageStore.$state.tabs.push(target);
  }
};
